package shiro;

import common.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import service.UserService;

public class ShiroDbRealm extends AuthorizingRealm{

    /**
     * 角色,权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //String username = JwtUtils.getUsername(principals.toString());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //这里可以连接数据库根据用户账户进行查询用户角色权限等信息,为简便,直接set
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addStringPermission("all");
        return simpleAuthorizationInfo;
    }

    /**
     * 自定义认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {

        UsernamePasswordToken token= (UsernamePasswordToken) auth;
        String username=token.getUsername();
        if(username==null){
            throw new UnknownAccountException("账号不正确");
        }else{
            if(username.equals("admin")){
                return new SimpleAuthenticationInfo(username, "admin", getName());
            }else if(username.equals("user")){
                return new SimpleAuthenticationInfo(username, "123456", getName());
            }else{
                User user = new UserService().getByEmail(username);
                if(user==null){
                    throw new UnknownAccountException("账号不正确");
                }else if(user.getPassword().equals(new String(token.getPassword()))){
                    return new SimpleAuthenticationInfo(user.getName(),user.getPassword(),getName());
                }else{
                    throw new UnknownAccountException("密码不正确");
                }
            }
        }
    }
}
